package com.ld.security.common.core.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

public class TemplateUtil {

  //	private static final VelocityEngine ve;
  //    private static final int charMargin = 32;
  //	static {
  //		ve = new VelocityEngine();
  //		ve.init();
  //	}
  //	static {
  //		//设置资源加载器
  //		Properties prop = new Properties();
  //		prop.put("file.resource.loader.class",
  // "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
  //		prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
  //		prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
  //
  //		Velocity.init(prop);
  //	}

  static Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);

  static {
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    configuration.setTemplateLoader(templateLoader);
    configuration.setDefaultEncoding("UTF-8");
  }

  /**
   * @param text 字符串模板
   * @param params 参数
   * @return
   */
  @SneakyThrows
  public static String renderString(String text, Map params) {
    StringWriter stringWriter = new StringWriter();
    Template template =
        new Template("xx", text, configuration);
    template.process(params, stringWriter);
    return stringWriter.toString();
  }

  /*    public static String renderString(String text,Map params) {
      VelocityContext context = new VelocityContext();
      params.forEach((x,y) -> {
          context.put(x.toString(), y);
      });

      StringWriter writer = new StringWriter();
      ve.evaluate(context, writer, "", text); // 关键方法
      return writer.toString();
  }*/

  private static Configuration conf = new Configuration();

  static {
      conf.setClassForTemplateLoading(TemplateUtil.class, "/");
  }

  @SneakyThrows
  public static String renderTemplate(String templatePath, Map<String, Object> args) {
    Template temp = conf.getTemplate(templatePath);
    temp.setEncoding("TF-8");
    Writer out = new StringWriter(2048);
    temp.process(args, out);

    return out.toString();
  }
  //        /**
  //         *
  //         * @param templatePath 模板路径
  //         * @param args 参数
  //         * @return
  //         */
  //    public static String renderTemplate(String templatePath,Map<String,Object> args)  {
  //        StringWriter sw = new StringWriter();
  //        Template tpl = Velocity.getTemplate(templatePath, "UTF-8");
  //        VelocityContext context = new VelocityContext(args);
  //        tpl.merge(context, sw);
  //        return sw.toString();
  //    }

  @SneakyThrows
  public static byte[] createTemplateZip(Map<String, String> map) {

    return StringUtil.createTemplateZip(map);
  }
}
